#include <iostream>

#include <cstring>

#include <dirent.h>

#include <sstream>  

#include <fstream>



#include <clang-c/Index.h>

using namespace std;



int numOfArgc = 0;



ostream& operator<<(ostream& stream, const CXString& str)

{

  stream << clang_getCString(str); //获取字符串的值（名称）

  clang_disposeString(str);

  return stream;

}



int main(int argc, char *argv[]) {

    if ((argc > 3) || (argc < 2)) {

        printf("You input wrong number arguments!\n");

        printf("%d\n",argc);

        return -1;

   }



ofstream outFile;

    outFile.open("/home/song/Desktop/llvm2/AST/build/AST.txt",ios::app); // 打开模式可省略  

outFile<<argv[1]<<" AST: "<<endl;



   numOfArgc = argc; //获取输入参数个数

  CXIndex index = clang_createIndex(0, 0); //创建翻译单元

  CXTranslationUnit unit = clang_parseTranslationUnit(//调用的libclang的函数，，解析翻译单元，第二个参数是要解析的文件名

   index, 0, argv, argc, 0, 0,

    CXTranslationUnit_None);

  if (unit == nullptr)

  {

    cerr << "Unable to parse translation unit. Quitting." << endl;

  return 0;

  }



  CXCursor cursor = clang_getTranslationUnitCursor(unit); //得到AST的根节点指针

  clang_visitChildren(  ////调用libclang函数访问根节点的孩子，参数为父节点、visitor访问函数和客户数据

    cursor,

    [](CXCursor c, CXCursor parent, CXClientData client_data)

    {



	//char str1[] = "abcdefg";

    	char str2[] = "lass";

        char* pc=new char[100];


        strcpy(pc,clang_getCString(clang_getCursorSpelling(c)));

        char*p2= strstr(pc, str2);

    ofstream outFile;

   
    outFile.open("/home/song/Desktop/llvm2/AST/build/AST.txt",ios::app); // 打开模式可省略  



    outFile<< "Name '" << clang_getCString(clang_getCursorSpelling(c)) << "',  Kind '" << clang_getCursorKindSpelling(clang_getCursorKind(c)) << "'\n";



outFile.close();

		



      cout << "Name '" << clang_getCString(clang_getCursorSpelling(c)) << "',  Kind '"

        << clang_getCursorKindSpelling(clang_getCursorKind(c)) << "'\n";

      return CXChildVisit_Recurse;

    },  //这就是visitor函数的内容，输出cursor节点的类型

    nullptr);



  clang_disposeTranslationUnit(unit); //销毁指定的CXTranslationUnit对象

  clang_disposeIndex(index); //销毁index

}